package com.sunagy.demand.backend.service.impl;

import com.sunagy.demand.backend.VO.response.CustomerProductResponseVO;
import com.sunagy.demand.backend.entity.CustomerProduct;
import com.sunagy.demand.backend.entity.Product;
import com.sunagy.demand.backend.repository.CustomerProductRepository;
import com.sunagy.demand.backend.repository.ProductRepository;
import com.sunagy.demand.backend.service.CustomerProductService;
import com.sunagy.demand.backend.service.CustomerProgressService;
import com.sunagy.demand.backend.utils.BeanUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

/**
 * desc：#TODO fill me ！
 * author：三餘無夢生
 * date：2018/5/10
 * time：下午1:37
 */
@Service
public class CustomerProductServiceImpl implements CustomerProductService {

    @Autowired
    private CustomerProductRepository customerProductRepository;

    @Autowired
    private CustomerProgressService customerProgressService;

    @Autowired
    private ProductRepository productRepository;
    @Override
    public List<CustomerProductResponseVO> getProductListByUserId(Integer userId) {
        List<CustomerProductResponseVO> customerProductDtoList = null;
        List<CustomerProduct> customerProductList = customerProductRepository.findByUserid(userId);
        customerProductDtoList = (List<CustomerProductResponseVO>) BeanUtil.copyPropertiesList(customerProductList,CustomerProductResponseVO.class);
        return customerProductDtoList;
    }

    @Override
    @Transactional
    public CustomerProductResponseVO pickProduct(Integer userId, Integer productId) {
        CustomerProduct customerProduct = customerProductRepository.findByUseridAndProductId(userId,productId);

        if (customerProduct == null){
            Product product = productRepository.findOne(productId);
            customerProduct = new CustomerProduct();
            customerProduct.setProductId(productId);
            customerProduct.setUserid(userId);
            customerProduct.setProductName(product.getProductname());
            customerProduct = customerProductRepository.save(customerProduct);
        }
        CustomerProductResponseVO customerProductResponseVO = new CustomerProductResponseVO();
        BeanUtil.copyProperties(customerProductResponseVO,customerProduct);
        return customerProductResponseVO;
    }

    @Override
    public List<CustomerProductResponseVO> pickProducts(Integer userId,Integer[] productIds) {
        List<CustomerProductResponseVO> customerProductResponseVOList = new ArrayList<>();
        for (Integer id : productIds) {
            customerProductResponseVOList.add(pickProduct(userId,id));
        }
        return customerProductResponseVOList;
    }
}
